package com.example.mytips.projectCreateActions;

import com.example.mytips.utils.CursorLineContent;
import com.example.mytips.utils.ReadFileUtil;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.newvfs.RefreshQueue;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class ExtensionInsertMethodAction extends AnAction {

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {

        Project project = e.getProject();
        assert project != null;

        // 获取项目根目录
        VirtualFile projectRoot = project.getBaseDir();

        ///上下文
        DataContext context = e.getDataContext();

        //编辑器
        Editor editor = CommonDataKeys.EDITOR.getData(context);
        if (editor == null) return;

        // 获取当前选中的文件集合
        VirtualFile[] files = e.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY);

        if (files != null && files.length == 1) {
            VirtualFile file = files[0]; // 假设只处理第一个选中的文件

            // 集合中的第一个
            VirtualFile parent = file.getParent();
            if (parent == null) return;

            if (!file.isDirectory()) {
                String[] split = file.getName().split("\\.");
                // 文件名
                String fileName = CreateExtensionAction.classSuffix + split[0];
                // 文件名带后缀
                String fileNameHasEnd = fileName + "." + file.getExtension();

                // 目标文件是否存在
                String targetPath = file.getParent().getPath() + File.separator + fileNameHasEnd;
                VirtualFile fileByPath = LocalFileSystem.getInstance().findFileByPath(targetPath);
                if (fileByPath == null) {
                    Messages.showInfoMessage(project, fileNameHasEnd + "文件不存在，请先创建", "操作失败");
                    return;
                }

                // 目标文件内容
                List<String> fileContents = ReadFileUtil.read(fileByPath);

                // 获得选中的方法名
                String methodName = getSelectMethod(editor, project);

                // 获取方法名后的注释
                String notes = getSelectMethodNotes(e);

                // 追加后的文件内容
                List<String> newFileContents = addMethod(fileContents, methodName, notes);

                ApplicationManager.getApplication().runWriteAction(new Runnable() {
                    @Override
                    public void run() {
                        // 这里放置需要执行的写操作
                        boolean write = ReadFileUtil.write(fileByPath, newFileContents);
                        if (write) {
                            Messages.showInfoMessage(project, fileNameHasEnd + "方法创建成功", "操作成功");
                        } else {
                            Messages.showInfoMessage(project, fileNameHasEnd + "方法创建失败", "操作失败");
                        }
                    }
                });

            }
        }
    }

    /// 获得选中的方法名
    private String getSelectMethod(Editor editor, Project project) {
        // 获取选中模型对象
        SelectionModel selectionModel = editor.getSelectionModel();
        if (selectionModel.hasSelection()) {
            // 获取选中的文本
            String selectedText = selectionModel.getSelectedText();
            if (selectedText != null && !selectedText.isEmpty()) {
                // 弹出对话框显示选中的文本
                return selectedText;
            }
        } else {
            // 没有选中文本时弹出提示
            Messages.showInfoMessage(project, "需要选定一个名字", "操作失败");
        }

        return "";
    }

    /// 获得选中的方法名后的注释
    private String getSelectMethodNotes(AnActionEvent e) {
        String line = CursorLineContent.getLineContent(e);
        String[] split = line.split("//");
        if (split.length >= 2) {
            return split[split.length - 1];
        }
        return "填写注释";
    }

    /// 给原始内容添加一个函数及注释
    private List<String> addMethod(List<String> list, String methodName, String notes) {
        int size = list.size();
        int index = -1;
        for (int i = size - 1; i >= 0; i--) {
            String line = list.get(i);
            boolean startsWith = line.trim().startsWith("}");
            if (startsWith) {
                index = i;
                break;
            }
        }

        if (index == -1) {
            return list;
        }

        list.add(index++, "");
        list.add(index++, "\t// " + notes);
        list.add(index++, "\tvoid " + methodName + "() {");
        list.add(index++, "\t\tprint('执行->" + methodName + "." + notes + "');");
        list.add(index++, "\t}");

        return list;
    }

}
